<template>
  <view class="search-box">
    <view class="search-box-inner">
      <!-- 使用 uni-ui 提供的搜索组件 -->
      <uni-search-bar
        @input="input"
        :radius="100"
        v-model="kw"
        cancelButton="none"
        placeholder="请输入搜索的内容"
        class="search-input"
      >
      </uni-search-bar>
      <button class="search-btn" @click="searchGroups">搜索</button>
    </view>
    <!-- 搜索建议列表的弹出层 -->
    <view class="sugg-list" v-if="showPopup == 1">
      <view class="uni-popper__arrow"></view>
      <view class="uni-combox__selector-scroll">
        <view
          class="uni-combox__selector-empty"
          v-if="searchResults.length === 0"
        >
          <text>无匹配项</text>
        </view>
        <view
          class="uni-combox__selector-item"
          v-for="(item, index) in searchResults"
          :key="index"
          @click="onSelectorClick(index)"
          v-else
        >
          <text>{{ item }}</text>
        </view>
      </view>
    </view>
    <view class="my_color" v-else-if="showPopup == 2">
      <view class="select-type">
        <view
          class="btn1"
          :class="{ selected: selectedButton === 'btn1' }"
          @click="selectButton('btn1')"
        >
          按内容查找
        </view>
        <view
          class="btn2"
          :class="{ selected: selectedButton === 'btn2' }"
          @click="selectButton('btn2')"
        >
          按标签查找
        </view>
        <view
          class="btn3"
          :class="{ selected: selectedButton === 'btn3' }"
          @click="selectButton('btn3')"
        >
          查找用户
        </view>
      </view>
      <view v-if="selectedButton==='btn1' || selectedButton==='btn2'" class="content">
        <!-- 组团信息列表显示区域 -->
        <view v-if="groupVoList.length > 0">
          <view
            v-for="(group, groupIndex) in groupVoList"
            :key="groupIndex"
            class="group-item"
            @click="getGroupDetail(group.tuanId)"
          >
            <view class="top-box">
              <image :src="group.avatar" class="avatar"></image>
              <view class="top-a">
                <view class="nickname">{{ group.name }}</view>
                <view class="send_time">{{ group.sendTime }}</view>
              </view>
            </view>
            <text class="tuan-title">
              {{
                group.expanded
                  ? group.tuanTitle
                  : group.tuanTitle.slice(0, 20) +
                    (group.tuanTitle.length > 20 ? "..." : "")
              }}
            </text>
            <br />

            <text class="tuan-detail">
              {{
                group.expanded
                  ? group.tuanDetail
                  : group.tuanDetail.slice(0, 80) +
                    (group.tuanDetail.length > 80 ? "..." : "")
              }}
            </text>
            <text v-if="group.tuanDetail.length > 80" class="toggle-btn"
              >详情</text
            >
            <!-- 添加 threeImages 显示 -->
            <view class="three-images">
              <image
                v-for="(image, imgIndex) in group.threeImages"
                :key="imgIndex"
                :src="image"
                class="theImage"
              ></image>
            </view>
          </view>
        </view>
        <view v-else class="no-content"> 暂无内容~ </view>
      </view>

      <view v-else-if="selectedButton==='btn3'">
        <view v-if="userList && userList.length > 0">
      <view v-for="(item, index) in userList" :key="index">

        <view class="his_info" @click="enterUserHome(item.userId)">
          <view class="his_avatar">
            <image :src="item.avatar" mode="aspectFill"></image>
          </view>
          <view class="his_name">{{item.userName}}</view>
        </view>
       
      </view>
    </view>
    <view v-else class="empty-follow">
      没有搜索到用户~
    </view>
      </view>
      <!-- 添加滚动加载提示 -->
      <view v-if="loadingMore" class="loading-more">加载中...</view>
    </view>
    <!-- 搜索历史 -->
    <view class="history-box" v-else-if="showPopup == 0">
      <!-- 标题区域 -->
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="17" @click="dialogToggle"></uni-icons>
      </view>
      <!-- 列表区域 -->
      <view class="history-list">
        <uni-tag
          :text="item"
          v-for="(item, i) in histories"
          :key="i"
          @click="searchByHistory(item)"
          style="margin-bottom: 10px"
        ></uni-tag>
      </view>
    </view>
    <uni-popup ref="alertDialog" type="dialog">
      <uni-popup-dialog
        :type="msgType"
        cancelText="取消"
        confirmText="继续"
        title="警告"
        content="此操作将会永久删除历史记录,是否继续？"
        @confirm="cleanHistory"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userId: "",
      // 延时器的 timerId
      timer: null,
      // 搜索关键词
      kw: "",
      // 搜索结果列表
      searchResults: [],
      // 搜索关键词的历史记录
      historyList: [],
      // 控制弹窗显示状态的属性
      showPopup: 0,
      // 查询对象，用于存储查询参数
      queryObj: {
        // 组团名称查询条件
        theKeyWord: "",
        // 分页查询的当前页数
        pageNum: 1,
        // 每页显示的组团数量
        pageSize: 10,
        userId: "",
      },
      // 组团列表，用于存储查询到的组团数据
      groupVoList: [],
      // 加载状态标志，用于显示加载中状态
      isLoading: false,
      // 选中的按钮
      selectedButton: 'btn1',
      userList: [],
    };
  },
  computed: {
    histories() {
      // 注意：由于数组是引用类型，所以不要直接基于原数组调用 reverse 方法，以免修改原数组中元素的顺序
      // 而是应该新建一个内存无关的数组，再进行 reverse 反转
      return [...this.historyList].reverse();
    },
  },
  onLoad() {
    
    if(this.userId = uni.getStorageSync("userId")){
      this.queryObj.userId = this.userId;
    }
    // 从本地缓存中获取关键词历史记录
    // 如果缓存中没有历史记录，则初始化为一个空数组
    this.historyList = JSON.parse(uni.getStorageSync("kw") || "[]");
  },
  /**
   * 页面触底时触发加载更多数据
   * 此函数主要用于处理用户滚动到页面底部时，自动加载更多数据的功能
   */
  onReachBottom() {
    // 检查是否有数据正在加载，如果是，则不执行任何操作
    if (this.isLoading) return;
    // 增加页码以便加载下一页数据
    this.queryObj.pageNum += 1;
    if(this.selectedButton==='btn1'){
      // 调用获取组团数据的方法
      this.getGroups();
    }else if(this.selectedButton==='btn2'){
      this.getByTag();
    }
    else if(this.selectedButton==='btn3'){
      this.getUser();
    }
    
  },
  methods: {
    searchByHistory(item) {
      console.log("点击历史搜索", item);
      // 更新搜索关键字
      this.kw = item;
      // 更新查询对象中的关键字字段
      this.queryObj.theKeyWord = this.kw;
      // 设置弹出层状态为2，表示历史记录搜索已执行
      this.showPopup = 2;
      // 清空搜索结果列表，准备接收新的搜索结果
      this.groupVoList = [];
      this.userList = [];
      // 重置分页参数到第1页
      this.queryObj.pageNum = 1;
    },

    async getGroups() {
      console.log('执行搜索', this.queryObj);
      this.isLoading = true;

      const { data: res } = await uni.$http.get(
        "/search/searchByName",
        this.queryObj
      );

      this.isLoading = false;
      // 如果搜索结果的数据部分不为空，将新搜索到的数据追加到groupVoList数组中
      if (res.data != null) this.groupVoList = [...this.groupVoList, ...res.data];
      console.log('搜索完成', res.data);
    },
    async getByTag() {
      console.log('执行根据标签搜索', this.queryObj);
      this.isLoading = true;

      const { data: res } = await uni.$http.get(
        "/search/searchByTag",
        this.queryObj
      );

      this.isLoading = false;
      // 如果搜索结果的数据部分不为空，将新搜索到的数据追加到groupVoList数组中
      if (res.data != null) this.groupVoList = [...this.groupVoList, ...res.data];
      console.log('搜索完成', res.data);
    },
   
    async getUser(){
      console.log('执行搜索用户', this.queryObj);
      this.isLoading = true;

      const { data: res } = await uni.$http.get(
        "/search/searchUser",
        this.queryObj
      );

      this.isLoading = false;
      // 如果搜索结果的数据部分不为空，将新搜索到的数据追加到groupVoList数组中
      if (res.data != null) this.userList = [...this.userList, ...res.data];
      console.log('搜索完成', res.data);
    },
  
    // 更新搜索关键字，并重置搜索状态以开始新的组团查询
    onSelectorClick(index) {
      console.log("选择搜索结果", index);
      this.kw = this.searchResults[index];
      this.queryObj.theKeyWord = this.kw;
      this.showPopup = 2;
      this.groupVoList = [];
      this.userList = [];
      this.queryObj.pageNum = 1;
      this.getGroups();
    },
    searchByTag() {
      this.selectedButton = 'btn2';
      this.queryObj.theKeyWord = this.kw;
      this.showPopup = 2;
      this.groupVoList = [];
      this.queryObj.pageNum = 1;
      this.getByTag();
    },
    searchGroups() {
      this.selectedButton = 'btn1';
      this.queryObj.theKeyWord = this.kw;
      this.showPopup = 2;
      this.groupVoList = [];
      this.queryObj.pageNum = 1;
      this.getGroups();
    },
    searchUser(){
      this.selectedButton = 'btn3';
      this.queryObj.theKeyWord = this.kw;
      this.showPopup = 2;
      this.userList = [];
      this.queryObj.pageNum = 1;
      this.getUser();
    },

    dialogToggle() {
      // 打开警告对话框
      this.$refs.alertDialog.open();
    },
    input(e) {
      this.showPopup = 1;
      // 清除 timer 对应的延时器
      clearTimeout(this.timer);
      // 重新启动一个延时器，并把 timerId 赋值给 this.timer
      this.timer = setTimeout(() => {
        this.kw = e;

        // 根据关键词，查询搜索建议列表
        this.getSearchList();
      }, 500);
    },
    // 根据搜索关键词，搜索组团建议列表
    async getSearchList() {
      // 判断关键词是否为空
      if (this.kw === "") {
        this.searchResults = [];
        this.showPopup = 0;
        return;
      }
      // 发起请求，获取搜索建议列表
      const { data: res } = await uni.$http.get("/search/searchByQuery", {
        query: this.kw,
      });
      // 检查响应状态码是否为200，若不是则显示错误消息并终止执行
      if (res.code !== 200) return uni.$showMsg();
      console.log(res);
      this.searchResults = res.data;

      this.saveSearchHistory();
    },

    // 保存搜索关键词为历史记录
    saveSearchHistory() {
      // this.historyList.push(this.kw)
      // 1. 将 Array 数组转化为 Set 对象
      const set = new Set(this.historyList);
      // 2. 调用 Set 对象的 delete 方法，移除对应的元素
      set.delete(this.kw);
      // 3. 调用 Set 对象的 add 方法，向 Set 中添加元素
      set.add(this.kw);
      // 4. 将 Set 对象转化为 Array 数组
      this.historyList = Array.from(set);
      // 调用 uni.setStorageSync(key, value) 将搜索历史记录持久化存储到本地
      uni.setStorageSync("kw", JSON.stringify(this.historyList));
    },
    // 清空搜索历史记录
    cleanHistory() {
      // 清空 data 中保存的搜索历史
      this.historyList = [];
      this.showPopup = 0;
      // 清空本地存储中记录的搜索历史
      uni.setStorageSync("kw", "[]");
    },

    // 获取组团详情
    getGroupDetail(tuanId) {
      uni.navigateTo({
        url: `/subpkg/group_detail/group_detail?tuanId=${tuanId}`,
      });
    },
    // 选择按钮
    selectButton(button) {
      this.selectedButton = button;
      if (button === 'btn1') {
        this.searchGroups();
      }else if (button === 'btn2') {
        this.searchByTag();
      }
       else if (button === 'btn3') {
        this.searchUser();
      }
    },
         //进入用户主页
         enterUserHome(theUserId) {
      uni.navigateTo({
        url: `/subpkg/user_home/user_home?theUserId=${theUserId}`,
      });
    },
  },
};
</script>

<style lang="scss">
.uni-searchbar {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  position: relative;
  padding: 16rpx 16rpx 0 16rpx;
  /* 将默认的 #FFFFFF 改为 #C00000 */
  background-color: #fbd269;
}

.search-box {
  position: sticky;
  top: 0;
  z-index: 999;
}

.sugg-list {
  padding: 0 5px;

  .sugg-item {
    font-size: 12px;
    padding: 13px 0;
    border-bottom: 1px solid #efefef;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .group-name {
      // 文字不允许换行（单行文本）
      white-space: nowrap;
      // 溢出部分隐藏
      overflow: hidden;
      // 文本溢出后，使用 ... 代替
      text-overflow: ellipsis;
      margin-right: 3px;
    }
  }
}

.history-box {
  padding: 0 5px;

  .history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    font-size: 13px;
    border-bottom: 1px solid #efefef;
  }

  .history-list {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 5px;

    .uni-tag {
      margin-top: 5px;
      margin-bottom: 5px;
      margin-right: 5px;
    }
  }
}

.uni-combox__selector-empty,
.uni-combox__selector-item {
  /* #ifndef APP-NVUE */
  display: flex;
  cursor: pointer;
  /* #endif */
  line-height: 36px;
  font-size: 14px;
  text-align: center;
  // border-bottom: solid 1px #DDDDDD;
  padding: 0px 10px;
}

.uni-combox__selector-item:hover {
  background-color: #f9f9f9;
}

.uni-combox__selector-empty:last-child,
.uni-combox__selector-item:last-child {
  /* #ifndef APP-NVUE */
  border-bottom: none;
  /* #endif */
}

.uni-popper__arrow,
.uni-popper__arrow::after {
  position: absolute;
  display: block;
  width: 0;
  height: 0;
  border-color: transparent;
  border-style: solid;
  border-width: 6px;
}
.uni-popper__arrow {
  filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));

  left: 10%;
  margin-right: 3px;
  border-top-width: 0;
  border-bottom-color: #ebeef5;
}

.uni-popper__arrow::after {
  content: " ";
  top: 1px;
  margin-left: -6px;
  border-top-width: 0;
  border-bottom-color: #fff;
}
.uni-combox__selector-scroll {
  box-sizing: border-box;
  position: absolute;
  top: calc(100% + 12px);
  left: 0;
  width: 100%;
  background-color: #ffffff;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 3;
  padding: 4px 0;
}
.search-box-inner {
  display: flex;
  background-color: #fbd269;
  justify-content: center;
  align-items: center;
  
  .search-input {
    width: 83vw;
  }
  .search-btn {
    width: 16vw;
    font-size: 14px;
    height: 36px;
    border-radius: 20px;
    background: rgb(249, 249, 249);
    color: #555555;
  }
}

.group-item {
  background-color: white;
  padding: 2vw;
  margin-bottom: 1.8vw;
  margin-left: 1.8vw;
  margin-right: 1.8vw;
  border-radius: 13px;

  .top-box {
    margin-top: 1px;
    height: 44px;
    width: 205px;
    display: flex;
    position: relative;
  }

  .avatar {
    display: block;
    width: 32px;
    height: 32px;
    border-radius: 50%;
  }

  .top-a {
    display: flex;
    flex-direction: column;
    padding-left: 10px;

    .nickname {
      color: #1d1c1c;
      font-size: 13px;
      max-width: 130px; /* 设置最大宽度 */
      white-space: nowrap; /* 防止换行 */
      overflow: hidden; /* 隐藏溢出内容 */
      text-overflow: ellipsis; /* 省略号显示 */
    }

    .send_time {
      color: #6a6666;
      font-size: 11px;
      margin-top: 2px;
    }
  }
}
.my_color {
  width: 100%;
  height: 150px; /* 设置view的总高度 */
  position: relative;
  background: linear-gradient(
    to bottom,
    rgb(251, 210, 105),
    rgb(245, 245, 245)
  );
}
.no-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 170px;
}

.tuan-title {
  font-weight: bold;
}

.tuanDetail {
  display: flex;
}

.toggle-btn {
  color: #1983f4;
  font-size: 16px;
  cursor: pointer;
  margin-top: 5px;
}

//  添加 threeImages 样式
.three-images {
  display: flex;
  margin-top: 10px;
}

.theImage {
  width: 29vw;
  height: 29vw;
  margin-right: 1vw;
  border-radius: 10px;
}
// 添加加载更多提示样式
.loading-more {
  text-align: center;
  padding: 10px;
  color: #6a6666;
}

.select-type {
  background: none;
  display: flex;
  padding-bottom: 10px;
  align-items: center;

  .btn1,
  .btn2,
  .btn3 {
    background: none;
    width: 33%;
    justify-content: center;
    align-items: center;
    text-align: center;
    padding: 10px;
    cursor: pointer;
    transition: background-color 0.3s;
  }

  .btn1.selected,
  .btn2.selected,
  .btn3.selected {
    background-color: #fbd269;
    border-color: #fbd269;
    font-weight: bold;
  }
}
.empty-follow {
  text-align: center;
  margin-top: 150px;
  color: rgb(130, 130, 130);
}

.his_info {
  background-color: #ffffff;
  display: flex;
  height: 70px;
  margin-bottom: 1px;
  width: 100%;

  .his_avatar {
    width: 50px;
    height: 50px;
    margin: 10px 10px;

    image {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }
  }

  .his_name {
    margin-top: 15px;
    white-space: nowrap; /* 防止换行 */
    overflow: hidden; /* 隐藏溢出内容 */
    text-overflow: ellipsis; /* 省略号显示 */
    width: 170px;
  }
}

</style>